# @FileName  :  resource.py
# @Time      :  2025/8/25
# @Author    :  Your Name
# @info      :  资源相关API接口

from typing import List
from fastapi import APIRouter, HTTPException, Query, Path, UploadFile, File
from app.schemas.resource import (
    ResourceCreate,
    ResourceUpdate,
    ResourceResponse,
    ResourceListResponse,
    ResourceQuery
)
from app.crud.resource import resource_crud
import os
import uuid

router = APIRouter(tags=["资源管理"])


@router.post("/", response_model=ResourceResponse, summary="创建资源")
async def create_resource(resource_data: ResourceCreate):
    """创建新资源"""
    try:
        resource = await resource_crud.create(resource_data)
        return resource
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建资源失败,{str(e)}")


@router.get("/", response_model=ResourceListResponse, summary="获取资源列表")
async def get_resources(
        name: str = Query(None, description="资源名称模糊查询"),
        code: str = Query(None, description="资源编码查询"),
        category_id: int = Query(None, description="分类查询"),
        teacher_id: int = Query(None, description="上传人查询"),
        course_id: int = Query(None, description="关联课程查询"),
        skip: int = Query(0, ge=0, description="跳过记录数"),
        limit: int = Query(10, ge=1, le=100, description="返回记录数")
):
    """获取资源列表，支持多条件查询和分页"""
    query = ResourceQuery(
        name=name,
        code=code,
        category_id=category_id,
        teacher_id=teacher_id,
        course_id=course_id,
        skip=skip,
        limit=limit
    )
    resources, total = await resource_crud.get_list(query)
    return ResourceListResponse(total=total, items=resources)


@router.get("/{resource_id}", response_model=ResourceResponse, summary="获取资源详情")
async def get_resource(
        resource_id: int = Path(..., description="资源ID")
):
    """根据ID获取资源详情"""
    resource = await resource_crud.get_by_id(resource_id)
    if not resource:
        raise HTTPException(status_code=404, detail="资源不存在")
    return resource


@router.get("/code/{code}", response_model=ResourceResponse, summary="根据编码获取资源")
async def get_resource_by_code(
        code: str = Path(..., description="资源编码")
):
    """根据编码获取资源详情"""
    resource = await resource_crud.get_by_code(code)
    if not resource:
        raise HTTPException(status_code=404, detail="资源不存在")
    return resource


@router.put("/{resource_id}", response_model=ResourceResponse, summary="更新资源信息")
async def update_resource(
        resource_data: ResourceUpdate,
        resource_id: int = Path(..., description="资源ID")
):
    """更新资源信息"""
    try:
        resource = await resource_crud.update(resource_id, resource_data)
        if not resource:
            raise HTTPException(status_code=404, detail="资源不存在")
        return resource
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新资源失败,{str(e)}")


@router.delete("/{resource_id}", summary="删除资源")
async def delete_resource(
        resource_id: int = Path(..., description="资源ID")
):
    """删除资源"""
    success = await resource_crud.delete(resource_id)
    if not success:
        raise HTTPException(status_code=404, detail="资源不存在")
    return {"message": "删除成功"}


@router.patch("/{resource_id}/increment-download", summary="增加下载次数")
async def increment_download_count(
        resource_id: int = Path(..., description="资源ID")
):
    """增加资源下载次数"""
    success = await resource_crud.increment_download_count(resource_id)
    if not success:
        raise HTTPException(status_code=404, detail="资源不存在")
    return {"message": "下载次数已更新"}


# 添加文件上传端点
@router.post("/upload-file/", summary="上传资源文件")
async def upload_file(file: UploadFile = File(...)):
    """上传资源文件到静态路径"""
    try:
        # 创建上传目录（如果不存在）
        upload_dir = "uploads"
        os.makedirs(upload_dir, exist_ok=True)

        # 生成唯一文件名
        file_extension = os.path.splitext(file.filename)[1]  # 获取文件扩展名
        unique_filename = f"{uuid.uuid4()}{file_extension}"  # 生成唯一文件名
        file_path = os.path.join(upload_dir, unique_filename)  # 生成文件路径

        # 保存文件
        with open(file_path, "wb") as buffer:  # 以二进制写入模式打开文件
            content = await file.read()  # 读取上传文件的所有内容
            buffer.write(content)  # 将内容写入到服务器文件中

        # 返回文件URL
        file_url = f"/{file_path}"  # 生成文件URL
        return {"url": file_url, "filename": file.filename}  # 返回文件URL和原始文件名
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"上传失败: {str(e)}")
